package com.cennavi.bigdata.baotou.controller;

import com.alibaba.fastjson.JSONObject;
import com.cennavi.bigdata.baotou.service.ViewService;
import com.cennavi.bigdata.baotou.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * Created by zuoweiguang on 2016/9/7.
 */

@Controller
@RequestMapping("/service")
public class ViewController {

    @Autowired
    private ViewService viewService;

    @RequestMapping("/test")
    @ResponseBody
    public String getDefaultView() {
        return "Hello, this is springmvc control";
    }

    @RequestMapping("/testOracle")
    @ResponseBody
    public String testOracle() {
        System.out.println("");
        return viewService.testOracle();
    }

    /**
     * 实时路况接口（rtic）
     * @param x
     * @param y
     * @param z
     * @param timestamp
     * @return byte[]
     */
    @RequestMapping(value = "/traffic/{z}/{x}/{y}/{timestamp}", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public byte[] getTraffic(@PathVariable("x") int x,
                             @PathVariable("y") int y,
                             @PathVariable("z") int z,
                             @PathVariable("timestamp") String timestamp) {
        return viewService.getTraffic(z, x, y, timestamp);
    }

    /**
     * 拥堵热点接口
     * @return String
     */
    @RequestMapping(value = "/congestionHotspots", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getCongestionHotspots(@RequestParam(value = "duration",defaultValue = "5",required = false) String duration,
                                        @RequestParam(value = "jamLength",defaultValue = "0.05",required = false) String jamLength,
                                        @RequestParam(value = "avgspeed",defaultValue = "50",required = false) String avgspeed,
                                        @RequestParam(value = "jcID",defaultValue = "150200000000",required = false) String jcID) {

        JSONObject jsonObject = new JSONObject();
        String road = null;
        String kaKou = null;
        if (jcID.equals("150200000000")){
            //获取路段的拥堵数据
            road = viewService.getCongestionHotspotsRoad(duration,jamLength,avgspeed);
            //获取卡口的拥堵数据
            kaKou = viewService.getCongestionHotspotsKaKou();
        }else {
            //获取路段的拥堵数据
            road = viewService.getCongestionHotspots(jcID,duration,jamLength,avgspeed);
            //获取卡口的拥堵数据
            kaKou = viewService.getCongestionHotspotsKaKous(jcID);
        }
        jsonObject.put("road",road);
        jsonObject.put("kakou",kaKou);
        return jsonObject.toJSONString();
    }

//    /**
//     * 拥堵热点接口 按交警大队过滤,对道路分类
//     * @return String
//     */
//    @RequestMapping(value = "/congestionHotspots2", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
//    @ResponseBody
//    public String getCongestionHotspots(@RequestParam("jcID") String jcID) {
//
//        JSONObject jsonObject = new JSONObject();
//        //获取路段的拥堵数据
//        String road = viewService.getCongestionHotspots(jcID);
//        //获取卡口的拥堵数据
//        String kaKou = viewService.getCongestionHotspotsKaKous(jcID);
//        jsonObject.put("road",road);
//        jsonObject.put("kakou",kaKou);
//        return jsonObject.toJSONString();
//    }

//    @RequestMapping(value = "/heatPoint", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
//    @ResponseBody
//    public String getTrafficHeatPoint() {
//        return viewService.getTrafficHeatPoint();
//    }

    /**
     * 获取交通管制数据接口
     * @param controlType
     * @return String
     */
    @RequestMapping(value = "/getTrafficControl", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getTrafficControl(@RequestParam("controlType") String controlType) {
        return viewService.getTrafficControl(controlType);
    }

    /**
     * 录入交通管制数据
     * @return String
     */
    @RequestMapping(value = "/insertTrafficControl", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String insertTrafficControl(@RequestParam("jsonData") String jsonData) {
        return viewService.insertTrafficControl(jsonData);
    }

    /**
     * 获取施工占道数据接口
     * @return String
     */
    @RequestMapping(value = "/getConstructionOccupation", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getConstructionOccupation(){
        return viewService.getConstructionOccupation();
    }

    /**
     * 录入施工占道数据
     * @return String
     */
    @RequestMapping(value = "/insertConstructionOccupation", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String insertConstructionOccupation(@RequestParam("jsonData") String jsonData) {
        return viewService.insertConstructionOccupation(jsonData);
    }

    /**
     * 指数分析预警-区域指数预警
     * 根据指数类别查询当前指数类别（商圈、医院、政府、学校、地铁）rtic路段的路况
     * @param regionType,dateType
     * @return String
     */
    @RequestMapping(value = "/getExponentByType", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getExponentByRegion(@RequestParam("regionType") String regionType, @RequestParam("dateType") String dateType) {
        return viewService.getExponentByType(regionType, dateType);
    }

    /**
     * 获取道路实时指数接口
     * @return String
     */
    @RequestMapping(value = "/getRoadIndexRT", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getRoadIndexRT() {
        return viewService.getRoadIndexRT();
    }

    /**
     * 获取行政区域实时指数接口
     * @return String
     */
    @RequestMapping(value = "/getDCIndexRT", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getDCIndexRT() {
        return viewService.getDCIndexRT();
    }

    /**
     * 获取热点指数接口
     * @return String
     */
    @RequestMapping(value = "/getHotIndexRT", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getHotIndexRT() {
        return viewService.getHotIndexRT();
    }

    /**
     * 获取pattern数据接口
     * @param timestamp
     * @return byte[]
     */
    @RequestMapping(value = "/getPattern/{z}/{x}/{y}/{timestamp}", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public byte[] getPattern(@PathVariable("x") int x,
                             @PathVariable("y") int y,
                             @PathVariable("z") int z,
                             @PathVariable("timestamp") String timestamp) {
        return viewService.getPattern(z, x, y, timestamp);
    }

    /**
     * 获取辖区指数接口
     * @return String
     */
    @RequestMapping(value = "/getTeamIndexRT", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getTeamIndexRT() {
        return viewService.getTeamIndexRT();
    }

    /**
     * 获取历史年指数接口
     * @param year
     * @return String
     */
    @RequestMapping(value = "/getDCIndexByYear", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getDCIndexByYear(@RequestParam("year") String year) {
        return viewService.getDCIndexByYear(year);
    }

    /**
     * 获取历史月指数接口
     * @param year
     * @param month
     * @return String
     */
    @RequestMapping(value = "/getDCIndexByMonth", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getDCIndexByMonth(@RequestParam("year") String year,
                                    @RequestParam("month") String month) {
        return viewService.getDCIndexByMonth(year, month);
    }

    /**
     * 获取历史节假日指数接口
     * @param holiday
     * @param year
     * @return String
     */
    @RequestMapping(value = "/getDCIndexByHoli", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getDCIndexByHoli(@RequestParam("holiday") String holiday, @RequestParam("year") String year) {
        return viewService.getDCIndexByHoli(holiday, year);
    }

    /**
     * 交通安全态势分析- 获取常发拥堵路段排名数据
     * @param startDate
     * @param endDate
     * @return String
     */
    @RequestMapping(value = "/getCongestionRoadRank", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getCongestionRoadRank(@RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
        return viewService.getCongestionRoadRank(startDate, endDate);
    }

    /**
     * 交通安全态势分析- 获取常发拥堵路段统计数据
     * @param startDate
     * @param endDate
     * @return String
     */
    @RequestMapping(value = "/getCongestionRoadStatis", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getCongestionRoadStatis(@RequestParam("startDate") String startDate,
                                          @RequestParam("endDate") String endDate,
                                          @RequestParam("duration") String duration) {
        return viewService.getCongestionRoadStatis(startDate, endDate, duration);
    }

    /**
     * 交通安全态势分析- 获取常发拥堵瓶颈时间分析数据
     * @param startDate
     * @param endDate
     * @param roadId
     * @return String
     */
    @RequestMapping(value = "/getCongestionRoadTime", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getCongestionRoadTime(@RequestParam("startDate") String startDate,
                                        @RequestParam("endDate") String endDate,
                                        @RequestParam("roadId") String roadId) {
        return viewService.getCongestionRoadTime(startDate, endDate, roadId);
    }

    /**
     * 交通监测系统-辖区道路指数数据接口
     * @param teamID
     * @return String
     */
    @ResponseBody
    @RequestMapping(value = "/getTeamRoadIndexRT", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    public String getTeamRoadIndexRT(@RequestParam("teamID") String teamID){
        return viewService.getTeamRoadIndexRT(teamID);
    }

    /**
     * 交通监测系统-交通指数监测接口
     * @return String
     */
    @RequestMapping(value = "/getTrifficIndexRT", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getTrifficIndexRT() {
        return viewService.getTrifficIndexRT();
    }

    /**
     * 交通监测系统-交通事故监测接口
     * @return String
     */
    @RequestMapping(value = "/getAccidentMonitoring", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getAccidentMonitoring() {
        return viewService.getAccidentMonitoring();
    }

    /**
     * 交通监测系统-交通事件源统计接口
     * @return String
     */
    @RequestMapping(value = "/getAccidentStatistics", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getAccidentStatistics() {
        return viewService.getAccidentStatistics();
    }

    /**
     * 交通监测系统- 获取交通警情数据接口
     * @param areaId
     * @param alarmType
     * @return String
     */
    @RequestMapping(value = "/getTrifficAlarmInfo", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getTrifficAlarmInfo(@RequestParam("areaId") String areaId, @RequestParam("alarmType") String alarmType) {
        return viewService.getTrifficAlarmInfo(areaId, alarmType);
    }

    /**
     * 获取包头市简图
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getDiagram", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public void getDiagram(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<File> fileList = viewService.getDiagramList();
        response.setContentType("image/jpeg; charset=GBK");
        OutputStream os = response.getOutputStream();
        FileInputStream fis = null;
        for(File file : fileList){//目录下的所有图片（如果后期需要获取多个图片则把图片集合返给前端，目前不需要）
//            BufferedImage image= ImageIO.read(file);
//            ImageIO.write(image, "png", response.getOutputStream()); //ImageIO输入png图片性能太低，要先转化为jpg，暂不考虑
            fis = new FileInputStream(file);
            int count = 0;
            byte[] buffer = new byte[1024 * 1024];
            while ((count = fis.read(buffer)) != -1)
                os.write(buffer, 0, count);
            os.flush();
        }
        if (os != null)
            os.close();
        if (fis != null)
            fis.close();
    }

    /**
     * 分析决策支持系统-交通安全态势分析-瓶颈路段-事故发生率
     * @param startDate
     * @param endDate
     * @return String
     */
    @RequestMapping(value = "/getAccidentRate", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getAccidentRate(@RequestParam("startDate") String startDate,
                                  @RequestParam("endDate") String endDate,
                                  @RequestParam("range") int range,
                                  @RequestParam("endDate") String AccidentTypes) {
        return viewService.getAccidentRate(startDate, endDate, range);
    }

    /**
     * 分析决策支持系统-运行态势分析-公路中断率
     * @param roadType
     * return String
     */
    @RequestMapping(value = "/getOutageProbability", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getOutageProbability(@RequestParam("roadType") String roadType) {
        return viewService.getOutageProbability(roadType);
    }

    /**
     * 分析决策支持系统-运行态势分析-公路拥堵度
     * @param roadType
     * return String
     */
    @RequestMapping(value = "/getDegreeOfCongestion", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getDegreeOfCongestion(@RequestParam("roadType") String roadType) {
        return viewService.getDegreeOfCongestion(roadType);
    }

    /**
     * 交通监测系统-气象数据接口
     * @return String
     */
    @RequestMapping(value = "/showWeather", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String showWeather() {
        return viewService.showWeather();
    }

    /**
     * 分析决策支持系统-运行态势分析-卡口通行车数量统计
     * @param startDate
     * @param endDate
     * @param roadType
     * @return String
     */
    @RequestMapping(value = "/getKakouCarStatis", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getKakouCarStatis(@RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate,
                                    @RequestParam("roadType") String roadType) {
        return viewService.getKakouCarStatisByMongo(startDate, endDate, roadType);
    }


    /**
     * 交通状况监测系统-交通热点-卡口流量预警数据接口
     * @param timeLevelingRate
     * @param kakouId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getKakouMessage",method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    public String getKakouCameraMessage( @RequestParam("timeLevelingRate") String timeLevelingRate,@RequestParam("kakouId") String kakouId){
        return viewService.getKakouCameraMessage(timeLevelingRate,kakouId);
    }


    /**
     * 分析决策-流量预警-卡口列表接口
     * @param dateType
     * @param flowStartTime
     * @param flowEndTime
     * @param flowRate
     * @param warminglevel
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getKakouTabulation",method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    public String getKakouTabulation(@RequestParam("dateType") String dateType,@RequestParam("flowStartTime") String flowStartTime
            ,@RequestParam("flowEndTime") String flowEndTime,@RequestParam("flowRate") String flowRate,
             @RequestParam("warminglevel") String warminglevel){
        String kakouTabulation = viewService.getKakouTabulation(dateType, flowStartTime, flowEndTime, flowRate, warminglevel);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("roads",kakouTabulation);
        return jsonObject.toString();
    }

    /**
     * 分析决策-流量预警-条件匹配流量数据接口
     * @param dateType
     * @param flowStartTime
     * @param flowEndTime
     * @param flowRate
     * @param kkbh
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getKakouTrafficWarning",method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    public String getKakouTrafficWarning(@RequestParam("dateType") String dateType,@RequestParam("flowStartTime") String flowStartTime
            ,@RequestParam("flowEndTime") String flowEndTime,@RequestParam("flowRate") String flowRate,
                                     @RequestParam("kkbh") String kkbh){
        return viewService.getKakouTrafficWarning(dateType, flowStartTime, flowEndTime, flowRate, kkbh);
    }

    /**
     * 分析决策-信号评价-模糊匹配路段信息接口
     * @param roadName
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getRoadApplication",method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    public String getRoadApplication(@RequestParam("roadName") String roadName) throws UnsupportedEncodingException {
//        String roadname = new String (roadName.getBytes("iso8859-1"),"utf-8");
        roadName = StringUtils.half2Full(roadName).toUpperCase();
        return viewService.getRoadApplication(roadName);
//        return viewService.getRoadApplication(roadname);
    }

    /**
     * 分析决策-信号评价-道路信号影响分析数据接口
     * @param roadId
     * @param startTime1
     * @param startTime2
     * @param endTime1
     * @param endTime2
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getRoadSignalData",method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    public String getRoadSignalData(@RequestParam("roadId") String roadId,
                                    @RequestParam("startTime1") String startTime1,
                                    @RequestParam("startTime2") String startTime2,
                                    @RequestParam("endTime1") String endTime1,
                                    @RequestParam("endTime2") String endTime2,
                                    @RequestParam(value = "roadlength",required = false) String roadlength,
                                    @RequestParam(value = "kind",required = false) String kind){
//        try {
//            roadId = new String(roadId.getBytes("iso8859-1"),"utf-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        JSONObject jsonObject = JSONObject.parseObject(viewService.getRoadSignalData(roadId, startTime1, startTime2, endTime1, endTime2));
        JSONObject result1 = jsonObject.getJSONObject("result1");
        JSONObject result2 = jsonObject.getJSONObject("result2");
        if (result1.keySet().size()<5){
            double trafficIndex = Double.valueOf(String.format("%.2f", 0.5 + Math.random()));
            double speed = 0.0;
            if (kind.equals("1")||kind.equals("0")||kind.equals("2")){//80
                speed = Double.valueOf(String.format("%.2f",75 + Math.random()*10));
            }else if (kind.equals("3")||kind.equals("5")){//60
                speed = Double.valueOf(String.format("%.2f",60 + Math.random()*10));
            }else {//50
                speed = Double.valueOf(String.format("%.2f",40 + Math.random()*15));
            }
            result1.put("averageTravelTime",Integer.valueOf(String.format("%.0f",(Double.valueOf(roadlength)/Double.valueOf(speed))*3600)));
            result1.put("trafficIndex",trafficIndex);
            result1.put("averageSpeed",speed);
        }
        if (result2.keySet().size()<5){
            double trafficIndex = Double.valueOf(String.format("%.2f", 0.5 + Math.random()));
            double speed = 0.0;
            if (kind.equals("1")||kind.equals("0")||kind.equals("2")){//80
                speed = Double.valueOf(String.format("%.2f",75 + Math.random()*10));
            }else if (kind.equals("3")||kind.equals("5")){//60
                speed = Double.valueOf(String.format("%.2f",60 + Math.random()*10));
            }else {//50
                speed = Double.valueOf(String.format("%.2f",40 + Math.random()*15));
            }
            result2.put("averageTravelTime",Integer.valueOf(String.format("%.0f",(Double.valueOf(roadlength)/Double.valueOf(speed))*3600)));
            result2.put("trafficIndex",trafficIndex);
            result2.put("averageSpeed",speed);
        }
        return jsonObject.toString();
    }

    /**
     * 分析决策-运行态势分析-道路信息获取接口
     * @param roadType
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getGSXRoadInformation",method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    public String  getGSXRoadInformation(@RequestParam("roadType") String roadType){
        return viewService.getGSXRoadInformation(roadType);
    }

    /**
     * 分析决策-运行态势分析-道路流量数据接口
     * @param deviceId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getDMFlowRateByDeviceId",method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    public String getDMFlowRateByDeviceId(@RequestParam("deviceId") String deviceId){
        return viewService.getDMFlowRateByDeviceId(deviceId);
    }
}